package com.dstats.fragments;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.dstats.Constants;
import com.dstats.MatchDetailsActivity;
import com.dstats.MatchsActivity;
import com.dstats.R;
import com.entities.MatchDetailed;
import com.entities.SteamUser;
import com.fetch.Fetch;
import com.fetch.FetchMatchsDetails;
import com.fetch.ImageLoader;
public class StatsFragment extends Fragment {

	public static final String PREFS_NAME = "statsPrefs";
	
	private static final String accIdSaved = "accId";
	private Spinner spinner;
	private Button button;
	private String selected;
	private ProgressDialog pDialog;
	private EditText edit;
	private TextView playerName;
	private ImageView playerImage;
	private ImageLoader imgLoader;
	private RelativeLayout savedLayout;
	
	private void getSavedUser(){
		SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);
		 String accSaved = settings.getString(accIdSaved, "");
		 if(!accSaved.isEmpty()){
			 imgLoader = new ImageLoader(getActivity());
			 new FetchSteamUser(accSaved).execute();
		 }
	}
	
	@Override
	public void onResume() {
		getSavedUser();
		super.onResume();
	}
	
	
	 public View onCreateView(LayoutInflater inflater, ViewGroup container,
             Bundle savedInstanceState) {
		 View rootView = inflater.inflate(R.layout.stats_layout, container, false);
		 spinner = (Spinner) rootView.findViewById(R.id.spinner1);
		 button = (Button) rootView.findViewById(R.id.buttonGo);
		 edit = (EditText) rootView.findViewById(R.id.editText1);
		 playerName = (TextView) rootView.findViewById(R.id.textViewSavedPlayer);
		 playerImage = (ImageView) rootView.findViewById(R.id.imageViewSavedPlayer);
		 savedLayout = (RelativeLayout) rootView.findViewById(R.id.savedPlayerLayout);
		 List<String> list = new ArrayList<String>();
		 list.add(getString(R.string.findByPlayerID));
		 list.add(getString(R.string.findByMatchID));


		 getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		 ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, list);
		 spinner.setAdapter(adapter);
		 spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			 
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
				selected = ((String) parent.getItemAtPosition(pos));
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
			 
		});
		 button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final String text = edit.getText().toString();
				if(selected.equals(getString(R.string.findByMatchID))){
					new FetchAndCheckMatchDetailed(text).execute();				

				} else if(selected.equals(getString(R.string.findByPlayerID))) {
					
					
					AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			        builder.setMessage(R.string.quertion_save)
			               .setPositiveButton(R.string.save_user, new DialogInterface.OnClickListener() {
			                   public void onClick(DialogInterface dialog, int id) {
			                	   SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);
			                	   SharedPreferences.Editor editor = settings.edit();
			  				     editor.putString(accIdSaved, text);
			  				     editor.commit();
			  				     
			  			
								Intent intent = new Intent(getActivity(), MatchsActivity.class);
								intent.putExtra("accId", text);
								startActivity(intent);
			                   }
			               })
			               .setNegativeButton(R.string.just_open, new DialogInterface.OnClickListener() {
			                   public void onClick(DialogInterface dialog, int id) {		
			                	   
			                	 
									Intent intent = new Intent(getActivity(), MatchsActivity.class);
									intent.putExtra("accId", text);
									startActivity(intent);
			                   }
			               });
			        
			        AlertDialog alertDialog = builder.create();
			        alertDialog.show();
						
					
				}
			}
		});
		 
		 return rootView;
	 }
	 
	 private void notFoundError(String error){
		 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setMessage(error)
			       .setCancelable(false)
			       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                //do things
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
	 }
	 
	 
	private class FetchAndCheckMatchDetailed extends FetchMatchsDetails{

		 @Override
		protected void onPreExecute() {
		        pDialog = new ProgressDialog(
		                getActivity());
		        pDialog.setMessage(getString(R.string.plsWait));
		        pDialog.setIndeterminate(true);
		        pDialog.setCancelable(false);		        
		        pDialog.show();
		}
		 @Override
		protected void onPostExecute(JSONObject result) {
			super.onPostExecute(result);
	
				try {
					JSONObject json = result.getJSONObject(Constants.RESULT);
					
					 if(json.has("error")){
						 notFoundError(json.getString("error"));
					 } else {
						MatchDetailsActivity.setMatch(new MatchDetailed(json));
						startActivity(new Intent(getActivity(), MatchDetailsActivity.class));
					 }
					
				} catch (JSONException e) {
					
					notFoundError("Error");
				}
			
			 pDialog.dismiss();

		}
		 
		public FetchAndCheckMatchDetailed(String matchId) {
			super(matchId);
		}
		 
	 }
	 
	private class FetchSteamUser extends Fetch{
		 private final String url = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/";
		 private final long convertTo64Bits =  Long.valueOf("76561197960265728");
		 private String userId;
			
			
			public FetchSteamUser(String userId) {
				 this.userId = String.valueOf(convertTo64Bits + Long.valueOf(userId));
				}
				
			@Override
			protected List<NameValuePair> getParams() {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair(Constants.KEY, Constants.apiKey));
				params.add(new BasicNameValuePair(Constants.STEAMIDS, userId));

				return params;
			}

			@Override
			protected String getUrl() {
				return url;
			}
			
			@Override
			protected void onPostExecute(JSONObject result) {
				super.onPostExecute(result);
				
					try {
						final SteamUser steamUser = new SteamUser(result.getJSONObject("response").getJSONArray("players").getJSONObject(0));
						String personaname = steamUser.getPersonaname();
						playerName.setText(personaname);
						playerName.setVisibility(View.VISIBLE);
						playerImage.setVisibility(View.VISIBLE);
						imgLoader.DisplayImage(steamUser.getAvatarUrl().split(".jpg")[0] + "_medium.jpg", playerImage);
						
						savedLayout.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								Intent intent = new Intent(getActivity(), MatchsActivity.class);
								intent.putExtra("title", steamUser.getPersonaname());
								intent.putExtra("avatarUrl", steamUser.getAvatarUrl());
								intent.putExtra("accId", String.valueOf(steamUser.getSteamId() - convertTo64Bits));
								startActivity(intent);
							}
						});
						
						} catch (JSONException e) {
							e.printStackTrace();
						}
					
				 
				
			}
			
		}

}
